import React, { PureComponent } from 'react';
import {
  Form, Input, Button, Card, Radio,
} from 'antd';
import FormBody from 'xrc-form';
import { routerRedux, Link } from 'dva/router';
import WrapItem from './WrapItem';

class Detail extends PureComponent {
  constructor(props) {
    super(props);

    const detail = this.props.detail || {};
    const defaultMemType = detail.MemType || (this.props.memberTypes[0] || {}).TypeId;

    this.state = {
      defaultMemType,
      cardTypePre: this.filterTypeName(defaultMemType, this.props.memberTypes),
    };
  }

  componentWillReceiveProps(nextProps) {
    if (!this.props.memberTypes || !this.props.memberTypes.length) {
      if (nextProps.memberTypes && nextProps.memberTypes.length) {
        const defaultMemType = nextProps.memberTypes[0].TypeId;

        this.setState({
          defaultMemType,
          cardTypePre: this.filterTypeName(defaultMemType, nextProps.memberTypes),
        });
      }
    }
  }

  genFields = () => {
    const {
      detail: data,
      memberTypes,
      dispatch,
      newCardNum,
      memberLevels,
      form,
    } = this.props;

    return [
      {
        name: 'MemId',
        options: {
          initialValue: data.MemId,
        },
      },
      {
        label: '会员类型',
        name: 'MemType',
        element: (
          <Radio.Group
            options={
              memberTypes.map(
                ({ TypeId: value, TypeName: label }) => ({ label, value, disabled: !!data.MemId }),
              )
            }
          />
        ),
        options: {
          initialValue: this.state.defaultMemType,
          onChange: (e) => {
            const cardTypePre = this.filterTypeName(e.target.value, memberTypes);
            this.setState({ cardTypePre });

            // 默认使用会员类型当做会员卡类型
            dispatch({ type: 'member/getCardNum', payload: e.target.value });
          },
          rules: [{
            required: true,
            message: '请选择会员类型',
          }],
        },
      },
      {
        label: '会员卡号',
        name: 'CardNum',
        element: <Input addonBefore={this.state.cardTypePre} placeholder="填写会员卡号" />,
        options: {
          initialValue: data.CardNum || newCardNum,
          rules: [{
            required: true,
            message: '请填写会员卡号',
          }],
        },
      },
      {
        label: '会员等级',
        name: 'LevelId',
        element: (
          <Radio.Group>
            {
              (memberLevels || []).map(
                ({ LevelId, Name }) => (
                  <Radio.Button key={LevelId} value={`${LevelId}`}>{Name}</Radio.Button>
                ),
              )
            }
          </Radio.Group>
        ),
        options: {
          initialValue: data.LevelId ? `${data.LevelId}` : '',
          rules: [{
            required: true,
            message: '请填写会员卡号',
          }],
        },
      },
      {
        label: '姓 名',
        name: 'Name',
        element: <Input placeholder="填写姓名" />,
        options: {
          initialValue: data.Name,
          rules: [{
            required: true,
            message: '请填写姓名',
          }],
        },
      },
      {
        label: '昵 称',
        name: 'NickyName',
        element: <Input placeholder="填写昵称" />,
        options: {
          initialValue: data.NickyName,
        },
      },
      {
        label: '身份证号',
        name: 'IdCard',
        element: <Input placeholder="请填写身份证" />,
        options: {
          initialValue: data.IdCard,
          rules: [{
            required: true,
            message: '请填写身份证号',
          }],
          onChange: (e) => {
            const idCardNo = e.target.value;

            if (idCardNo && idCardNo.length >= 18) {
              const birth = idCardNo.substr(6, 8);
              form.setFieldsValue({ Birthday: `${birth.substr(0, 4)}-${birth.substr(4, 2)}-${birth.substr(-2)}` });
            }
          },
        },
      },
      {
        label: '生日',
        name: 'Birthday',
        element: <Input disabled />,
        options: {
          initialValue: data.Birthday,
        },
      },
      {
        label: '护 照',
        name: 'Passport',
        element: <Input placeholder="请填写护照号" />,
        options: {
          initialValue: data.Passport,
        },
      },
      {
        label: '联系方式',
        name: 'Phone',
        element: <Input placeholder="请填写联系方式" />,
        options: {
          initialValue: data.Phone,
          rules: [{
            required: true,
            message: '请填写联系方式',
          }],
        },
      },
      {
        label: '联系地址',
        name: 'Address',
        element: <Input placeholder="请填写联系地址" />,
        options: {
          initialValue: data.Address,
        },
      },
      {
        label: '兴趣爱好',
        name: 'Interests',
        element: <Input.TextArea />,
        options: {
          initialValue: data.Interests,
        },
      },
      {
        label: '职 业',
        name: 'Profession',
        element: <Input />,
        options: {
          initialValue: data.Profession,
        },
      },
      {
        label: '特殊病/过敏史',
        name: 'DiseaseHistory',
        element: <Input.TextArea />,
        options: {
          initialValue: data.DiseaseHistory,
        },
      },
      {
        label: '备注',
        name: 'Remark',
        element: <Input.TextArea />,
        options: {
          initialValue: data.Remark,
        },
      },
      {
        label: '活动状态',
        name: 'Status',
        element: (
          <Radio.Group>
            <Radio value="0">待审核</Radio>
            <Radio value="1">正常</Radio>
            <Radio value="2">注销</Radio>
          </Radio.Group>
        ),
        options: {
          initialValue: `${data.Status}`,
        },
      },
      {
        element: (
          <div style={{ marginTop: 32 }}>
            <Button type="primary" htmlType="submit">提交</Button>
            <Button style={{ marginLeft: 8 }}>取消</Button>
          </div>
        ),
      },
    ];
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (err) {
        console.log(err);
        return false;
      }

      const params = {
        ...values,
        Status: values.Status - 0,
      };

      const action = params.MemId ? 'member/updateMember' : 'member/saveMember';

      this.props.dispatch({
        type: action,
        payload: {
          params,
          success: (data) => {
            const result = {
              type: 'success',
              title: '保存会员成功',
              actions: (
                <div>
                  <Link to="/member/list"><Button type="primary">查看列表</Button></Link>
                  <Link to={`/member/edit/${data.MemId}`}><Button>返回会员详情</Button></Link>
                </div>
              ),
            };

            this.props.dispatch({ type: 'result/updateResult', payload: result });
            this.props.dispatch(routerRedux.push('/result'));
          },
        },
      });
    });
  }

  filterTypeName = (typeId, memberTypes) => {
    return (memberTypes.filter(x => x.TypeId === typeId)[0] || {}).TypeName;
  }

  render () {
    const formProps = {
      items: this.genFields(),
      wrapItem: WrapItem,
      form: this.props.form,
    };

    return (
      <div>
        <Form onSubmit={this.handleSubmit}>
          <FormBody {...formProps} />
        </Form>
      </div>
    );
  }
}

export default Form.create()(Detail);
